// pages/user/user.js
import {
    OrderDetail
} from 'orderDetail-model.js'
import {
    hex_md5
} from '../../utils/md5.js'
var order = new OrderDetail();

const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        storeNo: '',
        employeNo: '',
        orderList: null,
        address: '',
        showAddressId: '',
        loadDone: false,
        allowClick: true,
        addressUrl: '',
        show_bottom_address: false,
        totalpay: 0,
        soldoutList: null,
        isShowIcon: false,
        showCouponDetail: false,
        couponList: null,
        originalTotalPrice: 0,
        isVip: 0,
        nowCouponList: null,
        isUseCoupon: true
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options)
        let id = options.orderId;
        let storeNo = 'S00000001';
        this.setData({
            storeNo,
            orderId: id
        });
        this._loadData();
        //   order.getMemberCouponsInfo({},res=>{
        //       this.setData({
        //           nowCouponList: res.data
        //       })
        //   })
    },
    onPageScroll(e) {
        // console.log(e)
        let status = false
        if (e.scrollTop > 50) {
            status = true
        } else {
            status = false
        }
        this.setData({
            show_bottom_address: status
        })

    },
    _loadData(callback, type) {
        let {
            storeNo,
            orderId
        } = this.data;
        let that = this,
            goodsNum = 0;
        let params = {
            "orderId": orderId,
            "storeNo": storeNo
        }
        if (!(type || type == 'pulldown')) {
            wx.showLoading({
                title: '加载中',
            })
        }
        order.getDetailList(params, res => {
            wx.hideLoading()
            if (res.status) {
                let postage = res.data.postage
                let data = res.data
                if (postage && postage == 'null') {
                    postage = 0
                }
                console.log('postage', postage)
                if (data.userAddressId) {
                    this.getAddrss(data.userAddressId)
                }
                let nowPrice;
                if (data.couponAmount) {
                    nowPrice = ((Number(data.orderPrice) + Number(postage)) * 1000 - (Number(data.couponAmount)) * 1000) / 1000
                } else {
                    nowPrice = Number(data.orderPrice) + Number(postage)
                }
                let originalTotalPrice = 0
                data.list.forEach(val => {
                    originalTotalPrice += val.original_price * val.goods_num
                })
                switch (data.orderStatus) {
                    case 'S':
                        data.orderStatusText = '支付成功';
                        break
                    case 'Q':
                        data.orderStatusText = '已取消';
                        break
                    case 'W':
                        data.orderStatusText = '待支付';
                        break
                    case 'F':
                        data.orderStatusText = '支付失败';
                        break
                    case 'RW':
                        data.orderStatusText = '申请退款';
                        break
                    case 'RU':
                        data.orderStatusText = '退款中';
                        break
                    case 'RS':
                        data.orderStatusText = '已退款';
                        break
                    case 'C':
                        data.orderStatusText = '已完成';
                        break
                    case 'RF':
                        data.orderStatusText = '退款失败';
                        break
                    case 'AU':
                        data.orderStatusText = '退款审核中';
                        break
                }
                this.setData({
                    originalTotalPrice,
                    vipDiscountTotal: (originalTotalPrice * 1000 - data.orderPrice * 1000) / 1000
                })
                // 测试用
                // data.logisticStatus = "LU"
                // data.orderStatus = "S"
                that.setData({
                    orderList: data ? data : "",
                    loadDone: true,
                    totalpay: nowPrice
                })
                console.log(data.orderStatus.search('R'), data.orderStatus != "Q")
                // 判断是否可切换地址
                let orderStatus = data.orderStatus,
                  logisticStatus = data.logisticStatus;
                if (orderStatus.search('R') < 0 && orderStatus !== "Q" && orderStatus !== "AU" && logisticStatus != "LU" && logisticStatus !== "LP" && orderStatus !== "S" && (logisticStatus === "LW" || orderStatus === "W" || orderStatus === "F")) {
                    this.setData({
                        isShowIcon: true
                    })
                }
                callback && callback()
            } else {
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
            }
        });

    },
    //   显示的时候判断是否有地址更新
    onShow() {
        let id = this.data.showAddressId
        if (id != '') {
            this.getAddrss(id)
        }
        this.setData({
            isVip: wx.getStorageSync('userStatus')
        })
    },
    //跳转到地址页面
    onselAddress() {
        let {
            orderList
        } = this.data;
        if (orderList.orderStatus == 'S' && orderList.logisticStatus == 'LW') {
            console.log('change')
            // 支付成功跳转到填写地址页面，三个选框，跟订单绑定
            // wx.navigateTo({
            //     url: '/pages/editAddress/editAddress?type=change&orderId=' + orderList.orderId
            // })
        } else if (orderList.orderStatus == 'W') {
            wx.navigateTo({
                url: '/pages/selAddress/selAddress?type=sel&orderId=' + orderList.orderId + '&addressId=' + orderList.userAddressId
            })
        }


    },
    //   封装根据id获取地址
    getAddrss(id) {
        let addressId = {
            "id": '' + id
        }
        order.getUserAddressById(addressId, resAddress => {
            if (resAddress.status) {
                this.setData({
                    address: resAddress.data,
                    loadDone: true
                })
            }
        })
    },
    getBackAddressId(id) {
        this.setData({
            showAddressId: id,
            'orderList.userAddressId': id
        })
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this._loadData(res => {
            wx.stopPullDownRefresh()
        }, 'pulldown')
    },
    wxPay(e) {
        console.log(e.detail.formId)
        let that = this
        let data = this.data
        let address = data.address
        let id = data.orderId
        let wxuid = wx.getStorageSync('wxUid');
        let allowClick = data.allowClick
        let params = {
            "wxuid": wxuid,
            "orderId": id,
            "contacts": address.contacts,
            "mobilePhone": address.mobilePhone,
            "detailedAddress": address.detailedAddress,
            "tradeType": "JSAPI"
        }
        this.setData({
            allowClick: false
        })

        if (!allowClick) {
            console.log('多点拦截')
            return
        } else if (data.orderList.orderStatus != 'S' && (data.orderList.userAddressId == '' || data.address.status == 1)) {
            wx.showToast({
                title: '请先选择地址',
                icon: 'none'
            })
            that.setData({
                allowClick: true
            })
        } else {
            wx.showLoading({
                title: '加载中',
            })
            console.log('click')
            order.wxPay(params, res => {
                wx.hideLoading()
                console.log(res)
                if (res.status) {
                    let data = res.data
                    if(data.couponDirectPay === 'SUCCESS'){
                        order.reduceGoodsStock({
                            orderId: id,
                            formId: e.detail.formId
                        }, reduce => {
                            that._loadData(()=>{
                                wx.showToast({
                                    title: '支付成功',
                                })
                                that.setData({
                                    isShowIcon: false
                                })
                            });
                        })
                        return
                    }
                    console.log('res', res, res.data, 'prepay_id=' + data.miniPaySign)
                    if (data.result_code == "SUCCESS" && data.return_code == "SUCCESS") {
                        console.log('success')
                        wx.requestPayment({
                            'timeStamp': '' + data.miniTimeStamp,
                            'nonceStr': '' + data.miniNonceStr,
                            'package': 'prepay_id=' + data.prepay_id,
                            'signType': 'MD5',
                            'paySign': '' + data.miniPaySign,
                            'success': function (result) {
                                console.log('pay', result)
                                that.setData({
                                    'orderList.orderStatus': 'S',
                                    'orderList.orderStatusText':'支付成功',
                                    "isShowIcon": false,
                                    "orderList.contacts": address.contacts,
                                    "orderList.mobilePhone": address.mobilePhone,
                                    "orderList.detailedAddress": address.detailedAddress,
                                })
                                wx.showToast({
                                    title: '支付成功',
                                })
                                order.reduceGoodsStock({
                                    orderId: id,
                                    formId: e.detail.formId
                                }, reduce => {
                                    // that._loadData(()=>{
                                   
                                    // });
                                })
                                app.aldstat.sendEvent('立即支付', data.employeNo);
                            },
                            'fail': function (result) {
                                that.setData({
                                    allowClick: true
                                })

                            }
                        })
                    } else if (data.stockList && data.stockList.length > 0) {
                        console.log(data.stockList)
                        this.setData({
                            soldoutList: data.stockList,
                            allowClick: true
                        })
                    }
                } else {
                    wx.hideLoading()
                    wx.showToast({
                        title: '服务器错误',
                        icon: 'none'
                    })
                    this.setData({
                        allowClick: true
                    })
                }
            })
        }
    },
    //   购买会员
    vipPay(e) {
        if (wx.getStorageSync('userStatus') == 1) {
            wx.showToast({
                title: '您已经是会员!',
            })
            return
        }
        console.log(e.detail.formId)
        let that = this
        let data = this.data
        let id = data.orderId
        let wxuid = wx.getStorageSync('wxUid');
        let allowClick = data.allowClick
        let params = {
            "wxuid": wxuid,
            "orderId": id,
        }
        this.setData({
            allowClick: false
        })

        if (!allowClick) {
            console.log('多点拦截')
            return
        } else {
            wx.showLoading({
                title: '加载中',
            })
            console.log('click')
            order.doUnifiedOrderForRechargeMember(params, res => {
                wx.hideLoading()
                console.log(res)
                if (res.status) {
                    let data = res.data
                    console.log('res', res, res.data, 'prepay_id=' + data.miniPaySign)
                    if (data.result_code == "SUCCESS" && data.return_code == "SUCCESS") {
                        console.log('success')
                        wx.requestPayment({
                            'timeStamp': '' + data.miniTimeStamp,
                            'nonceStr': '' + data.miniNonceStr,
                            'package': 'prepay_id=' + data.prepay_id,
                            'signType': 'MD5',
                            'paySign': '' + data.miniPaySign,
                            'success': function (result) {
                                console.log('pay', result)
                                wx.setStorageSync('userStatus', 1);
                                that.setData({
                                    'orderList.orderStatus': 'C'
                                })
                                wx.showToast({
                                    title: '购买会员成功',
                                })
                            },
                            'fail': function (result) {
                                that.setData({
                                    allowClick: true
                                })
                            }
                        })
                    } else if (data.stockList && data.stockList.length > 0) {
                        console.log(data.stockList)
                        this.setData({
                            soldoutList: data.stockList,
                            allowClick: true
                        })
                    }
                } else {
                    wx.hideLoading()
                    wx.showToast({
                        title: '服务器错误',
                        icon: 'none'
                    })
                    this.setData({
                        allowClick: true
                    })
                }
            })
        }
    },
    soldoutBack() {
        this.setData({
            soldoutList: null,
            allowClick: true

        })
    },
    /// 切换显示优惠券
    toggleCoupon(e) {
        let {
            showCouponDetail,
            orderList
        } = this.data
        if (!showCouponDetail) {
            let params = {
                orderId: orderList.orderId
            }
            order.orderCouponList(params, res => {
                if (res.status) {
                    if (res.data.length == 0) {
                        wx.showToast({
                            title: '当前无可用优惠券!',
                            icon: 'none'
                        })
                        return
                    }
                    res.data.forEach(val => {
                        val.startTime = order.formate(val.startTime, 'yyyy-MM-dd')
                        val.endTime = order.formate(val.endTime, 'yyyy-MM-dd')
                        if (val.pcuEndTime && val.pcuStartTime) {
                            val.pcuEndTime = order.formate(val.pcuEndTime, 'yyyy-MM-dd')
                            val.pcuStartTime = order.formate(val.pcuStartTime, 'yyyy-MM-dd')
                        }
                    })
                    this.setData({
                        showCouponDetail: true,
                        couponList: res.data
                    })
                } else {
                    wx.showToast({
                        title: '服务器错误',
                        icon: 'none'
                    })
                }
            })
        } else {
            this.setData({
                showCouponDetail: false
            })
        }

    },
    // 使用优惠券
    useCoupon(e) {
        let id = order.getDataSet(e, 'id')
        let index = order.getDataSet(e, 'index')
        let couponAmount = order.getDataSet(e, 'price'); //当前优惠券金额
        let {
            orderList,
            couponList
        } = this.data
        let params = {
            "orderId": orderList.orderId,
            "couponId": '' + id,
            "lastCouponId": '' + orderList.couponId,
            "action": "1",
            "couponAmount": +couponAmount,
            "lastCouponAmount": +orderList.couponAmount,
        }
        if (!orderList.couponId) {
            delete params.lastCouponId
            delete params.lastCouponAmount
        }
        wx.showLoading({
            title: '加载中',
        })
        order.orderCouponUse(params, res => {
            wx.hideLoading()
            if (res.status) {
                this._loadData()
                couponList.forEach(val => {
                    if (val.id == id) {
                        val.isUsed = 0
                    } else {
                        val.isUsed = 1
                    }
                })
                this.setData({
                    couponList,
                    showCouponDetail: false
                })
            } else {
                wx.showToast({
                    icon: 'none',
                    title: '服务器错误',
                })
            }
        })
    },
    //   不使用优惠券
    notUseCoupon() {
        let {
            orderList
        } = this.data
        let params
        //   if(Object)
        console.log(Object.keys(orderList).indexOf('couponId'))
        if (Object.keys(orderList).indexOf('couponId') < 0) {
            this.setData({
                showCouponDetail: false
            })
        } else {
            params = {
                "orderId": '' + orderList.orderId,
                "action": '2',
                "lastCouponId": '' + orderList.couponId,
                "lastCouponAmount": +orderList.couponAmount
            }
            order.orderCouponUse(params, res => {
                if (res.status) {
                    this._loadData()
                    this.setData({
                        showCouponDetail: false
                    })
                } else {
                    wx.showToast({
                        title: '服务器错误',
                        icon: 'none'
                    })
                }
            })
        }
    },
    useChange() {
        let {
            isUseCoupon
        } = this.data
        this.setData({
            isUseCoupon: !isUseCoupon
        })
    },
    // 复制订单号
    copyOrderId(e){
        let id = order.getDataSet(e,'id');
        wx.setClipboardData({
            data: id,
            success: function (res) {
                wx.showToast({
                    title: '复制成功',
                })
            }
        })
    }

})